<?php
namespace Api\Controller;

use Think\Controller;

/**
 * 商品
 */
class GoodsController extends CommonController
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 商品详情
     * @return [type] [description]
     */
    public function index()
    {
        $goods_id = I('post.id', 0, 'intval');

        $goods = D('Api/Goods', 'Service')->detail($goods_id);

        if (!$goods) {
            error(8018, '');
        } else {
            success($goods);
        }
    }

    /**
     * 商品评论
     * @return [type] [description]
     */
    public function review()
    {
        $id   = I('post.goods_id', 1, 'intval');
        $page = I('post.page', 1, 'intval');

        $reviews = D('Api/Review', 'Service')->a();

        success($reviews);
    }

    /**
     * 查找商品
     * @return [type] [description]
     */
    public function search()
    {
        $data = [
            'category_id' => $category_id = I('post.category_id', 0, 'intval'),
            'keyword'     => $keyword = I('post.keyword', ''),
            'sort'        => $sort = I('post.sort', 'default', 'trim'),
            'order'       => $order = I('post.order', 'asc', 'trim'),
            'page'        => $page = I('post.page', 1, 'intval'),
        ];

        if (!in_array($sort, ['default', 'sales', 'price', 'new'])) {
            error(8021, '排序类型错误');
        }

        if (!in_array($order, ['asc', 'desc'])) {
            error(8022, '排序顺序错误');
        }

        $goods = D('Api/Goods', 'Service')->search($data);
        success($goods);
    }

    /**
     * 添加商品浏览记录
     * @return [type] [description]
     */
    public function addHistory()
    {
        $id = I('post.id', 0, 'intval');

        $ext = [
            'device'  => DEVICE,
            'uuid'    => UUID,
            'version' => VERSION,
            'ip'      => get_client_ip(),
        ];
        D('Api/Goods', 'Service')->addHistory(USER_ID, $id, $ext);

        success();
    }

    /**
     * 商品浏览记录
     * @return [type] [description]
     */
    public function history()
    {
        $history = D('Api/Goods', 'Service')->history(USER_ID);

        success($history);
    }

    /**
     * 查看商品属性规格
     * @return [type] [description]
     */
    public function specItem()
    {
        $id = I('post.id', 0, 'intval');

        $spec = D('Api/Goods', 'Service')->specItem($id);

        success($spec);
    }
}
